package com.app.asktom;

import java.util.Map;

import org.xmlpull.v1.XmlPullParser;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Shader;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Xml;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.app.asktom.abs.AbsHttpAsync;
import com.app.asktom.component.Config;
import com.app.asktom.component.DeviceHelper;
import com.app.asktom.component.HttpHelper;
import com.app.asktom.component.ImageLoader;
import com.app.asktom.component.JsonHelper;
import com.app.asktom.model.User;

public class ViewDetailActivity extends Activity implements DialogInterface.OnClickListener, OnClickListener{

	private ImageView imageView;
	private TextView foodTitle;
	private RatingBar spoon;
	private LinearLayout spoonLayout;
	EditText foodNameUpdated;
	
	private AlertDialog.Builder actionBuilder, deleteBuilder, spoonBuilder, updateBuilder;
	
	protected ViewDetailActivity viewDetailActivity;
	
	private String foodId;
	private String response;
	private String coords;
	private String foodName;
	
	CharSequence[] items;
	
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_detail);
		// Show the Up button in the action bar.
		foodTitle = (TextView) findViewById(R.id.txtFoodTitle);
		viewDetailActivity = this;
		Bundle extras;
		
		if(savedInstanceState == null) {
			extras = getIntent().getExtras();
			String url = extras.getString("url");
			Log.d("DEBUG","=====url " + extras.getString("url"));
			foodName = extras.getString("picName");
			foodTitle.setText(foodName);
			this.foodId = extras.getString("id");
			if(extras.getString("uploaderNum").equals("ME")) items = new CharSequence[]{"Spoon", "Update", "Delete", "Cancel"};
			else items = new CharSequence[]{"Spoon", "Cancel"};
			this.coords = extras.getString("coords");
//			byte[] byteArray = extras.getByteArray("picture");
//			Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
			imageView = (ImageView) findViewById(R.id.imgPhoto);
//			Bitmap bit = Bitmap.createBitmap(BitmapFactory.decodeFile(extras.getString("url")));
//			imgView.setImageBitmap(bmp);
			
			ImageLoader imageLoader = new ImageLoader(this);
			imageLoader.DisplayImage(url, imageView);
			
			imageView.setOnClickListener(this);
			
//			URL url2;
//			try {
//				url2 = new URL(url);
//				Bitmap bmp = BitmapFactory.decodeStream(url2.openConnection().getInputStream());
//				imageView.setImageBitmap(bmp);			
//			} catch (MalformedURLException e) {
//				e.printStackTrace();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
			
		} else {
			
		}
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.view_detail, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@SuppressLint("NewApi")
	@Override
	public void onClick(DialogInterface dialog, int which) {
		// TODO Auto-generated method stub
		if("Cancel".equals(items[which])){
			dialog.cancel();
		} else if("Delete".equals(items[which])){
			deleteBuilder = new AlertDialog.Builder(this);
			deleteBuilder.setTitle("Delete Image");
			deleteBuilder.setMessage("Are you sure on deleting this food?");
			deleteBuilder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					DeleteFoodTask deleteFood = new DeleteFoodTask();
					deleteFood.setActivity(viewDetailActivity);
					deleteFood.execute();
				}
				
			});
			
			deleteBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			});
			dialog.dismiss();
			deleteBuilder.show();
		} else if("Spoon".equals(items[which])){
			spoonBuilder = new AlertDialog.Builder(this);
			
//			spoon = (RatingBar) findViewById(R.id.ratingBar1);
			Resources resources = getResources();
			XmlPullParser parser = resources.getXml(R.drawable.ratingbar_red);
			AttributeSet attributes = Xml.asAttributeSet(parser);
			spoon = new RatingBar(this,attributes);
			
//			spoon.setBackground(getResources().getDrawable(R.drawable.spoon_fork_off));
//			spoon.setBackgroundResource(R.drawable.spoon_fork_off);
//			spoon.setProgressDrawable(getResources().getDrawable(R.drawable.spoon_fork_off));
//			spoon.setSecondaryProgress(R.drawable.spoon_fork);
//			spoon.setIndeterminateDrawable(getResources().getDrawable(R.drawable.spoon_fork_off));
			spoon.setStepSize(1);
			spoon.setNumStars(5);
			Bitmap[] images = new Bitmap[3];
			images[0] = BitmapFactory.decodeResource(getResources(),R.drawable.spoon_fork_off);
			images[1] = BitmapFactory.decodeResource(getResources(),R.drawable.spoon_fork);
			images[2] = BitmapFactory.decodeResource(getResources(),R.drawable.spoon_fork);
			spoon.setProgressDrawable(buildRatingBarDrawables(images));
			
//			spoon.setBackgroundDrawable(getResources().getDrawable(R.drawable.spoon_fork_off));
//			spoon.setBackground(getResources().getDrawable(R.drawable.spoon_fork_off));
//			spoon.setSecondaryProgress(R.drawable.spoon_fork_off);
//			spoon.setProgress(R.drawable.spoon_fork);
			spoon.setLayoutParams(new LayoutParams(500, 80));
//			spoon.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			spoonLayout = new LinearLayout(this);
			spoonLayout.setGravity(Gravity.CENTER);
			spoonLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
			spoonLayout.addView(spoon);
			spoonBuilder.setView(spoonLayout);
			spoonBuilder.setPositiveButton("Spoon", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					SpoonFoodTask spoonFood = new SpoonFoodTask();
					spoonFood.setActivity(viewDetailActivity);
					spoonFood.execute(String.valueOf(spoon.getRating()));
				}
			});
			
			spoonBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			});
			
			dialog.dismiss();
			spoonBuilder.show();
		} else if("Update".equals(items[which])){
			
			updateBuilder = new AlertDialog.Builder(this);
			LinearLayout updateLayout = new LinearLayout(this);
			foodNameUpdated = new EditText(this);
			foodNameUpdated.setText(this.foodName);
			foodNameUpdated.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
			updateLayout.addView(foodNameUpdated);
			updateBuilder.setView(updateLayout);
			updateBuilder.setPositiveButton("Update", new DialogInterface.OnClickListener(){
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					UpdateFoodTask updateFood = new UpdateFoodTask();
					updateFood.setActivity(viewDetailActivity);
					updateFood.execute(String.valueOf(foodNameUpdated.getText()));
					
				}
				
			});
			updateBuilder.setNeutralButton("Location", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

				}
			});
			updateBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			});
			updateBuilder.setMessage("Update");
			AlertDialog dl = updateBuilder.create();
			dl.show();
			//Overriding the handler immediately after show is probably a better approach than OnShowListener as described below
			dl.getButton(AlertDialog.BUTTON_NEUTRAL).setOnClickListener(new View.OnClickListener() {            
	          @Override
	          public void onClick(View v) {
					Intent intent = new Intent(viewDetailActivity,UpdateMapCoordinateActivity.class);
					startActivity(intent);
	          }
	       });
			
			
//			updateBuilder = new AlertDialog.Builder(this);
//			updateBuilder.setTitle("Update:");
//			LinearLayout updateLayout = new LinearLayout(this);
//			foodNameUpdated = new EditText(this);
//			foodNameUpdated.setText(this.foodName);
//			foodNameUpdated.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
//			updateLayout.addView(foodNameUpdated);
//			updateBuilder.setView(updateLayout);
//			updateBuilder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
//				
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					// TODO Auto-generated method stub
//					UpdateFoodTask updateFood = new UpdateFoodTask();
//					updateFood.setActivity(viewDetailActivity);
//					updateFood.execute(String.valueOf(foodNameUpdated.getText()));
//				}
//			});
//			
//			updateBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
//				
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					// TODO Auto-generated method stub
//					
//				}
//			});
//			
//			
//			
//			updateBuilder.setNeutralButton("Location", new DialogInterface.OnClickListener() {
//				
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					// TODO Auto-generated method stub
//					Intent intent = new Intent(viewDetailActivity,UpdateMapCoordinateActivity.class);
//					startActivity(intent);
//				}
//			});
//
//			dialog.dismiss();
//			updateBuilder.show();
			
		}
	}

	private Drawable buildRatingBarDrawables(Bitmap[] images) {
	    final int[] requiredIds = { R.drawable.spoon_fork_off,
	    		R.drawable.spoon_fork, R.drawable.spoon_fork };
	    final float[] roundedCorners = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 };
	    Drawable[] pieces = new Drawable[3];
	    for (int i = 0; i < 3; i++) {
	        ShapeDrawable sd = new ShapeDrawable(new RoundRectShape(
	                roundedCorners, null, null));
	        BitmapShader bitmapShader = new BitmapShader(images[i],
	        		Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
	        sd.getPaint().setShader(bitmapShader);
	        ClipDrawable cd = new ClipDrawable(sd, Gravity.LEFT,
	                ClipDrawable.HORIZONTAL);
	        if (i == 0) {
	            pieces[i] = sd;
	        } else {
	            pieces[i] = cd;
	        }
	    }
	    LayerDrawable ld = new LayerDrawable(pieces);
	    for (int i = 0; i < 3; i++) {
	        ld.setId(i, requiredIds[i]);
	    }
	    return ld;
	}	
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		switch(v.getId()){
		case R.id.imgPhoto:
			actionBuilder = new AlertDialog.Builder(this);
			actionBuilder.setTitle("Actions:");
			actionBuilder.setItems(items, this);
			actionBuilder.show();
			break;
		}
	}
	
	public class UpdateFoodTask extends AbsHttpAsync{
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			if(this.getResponse() != null &&
					!this.getResponse().startsWith("error:")) {
				Map<String, String> res = JsonHelper.getInstance().reponseGetStat(this.getResponse());
				Toast toast = Toast.makeText(getApplicationContext(), res.get("msg"), Toast.LENGTH_SHORT);
				toast.show();
				
				if(res.get("stat").equals("OK")){
					Intent viewFood = new Intent(getApplicationContext(), ViewFoodActivity.class);
					viewFood.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(viewFood);
				}
			}
			super.onPostExecute(result);
		}

		@Override
		protected String doInBackground(String... params) {

			if(!DeviceHelper.getUpdateLatitude().equals("")) {
				coords = DeviceHelper.getUpdateLatitude()  + "," + DeviceHelper.getUpdateLongitude();
				DeviceHelper.storeUpdateLocation(0, 0);
			}
			
			User user = new User(getApplicationContext());
			Map<String, String> map = user.getUserInfo();
			HttpHelper httpHelper = new HttpHelper();
			httpHelper.setPost(true);
			httpHelper.setUrl(Config.getInstance().get("baseUrl"));
			httpHelper.setPostParam("appId", "WBTOM");
			httpHelper.setPostParam("req", "UPD");
			httpHelper.setPostParam("user", map.get("phoneNumber"));
			httpHelper.setPostParam("pass", map.get("password"));
			httpHelper.setPostParam("id", foodId);
			httpHelper.setPostParam("coord", coords);
			httpHelper.setPostParam("categ", "FOOD");
			httpHelper.setPostParam("name", params[0]);
			httpHelper.sendRequest();
			Log.i("TASKS", httpHelper.getResponse());
			this.setResponse(httpHelper.getResponse());
			return this.getResponse();
		}
		
	}
	
	public class DeleteFoodTask extends AbsHttpAsync{
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			if(this.getResponse() != null &&
					!this.getResponse().startsWith("error:")) {
				Map<String, String> res = JsonHelper.getInstance().reponseGetStat(this.getResponse());
				Toast toast = Toast.makeText(getApplicationContext(), res.get("msg"), Toast.LENGTH_SHORT);
				toast.show();
				
				if(res.get("stat").equals("OK")){
					Intent viewFood = new Intent(getApplicationContext(), ViewFoodActivity.class);
					viewFood.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(viewFood);
				}
			}
			super.onPostExecute(result);
		}

		@Override
		protected String doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			User user = new User(getApplicationContext());
			Map<String, String> map = user.getUserInfo();
			HttpHelper httpHelper = new HttpHelper();
			httpHelper.setPost(true);
			httpHelper.setUrl(Config.getInstance().get("baseUrl"));
			httpHelper.setPostParam("appId", "WBTOM");
			httpHelper.setPostParam("req", "DEL");
			httpHelper.setPostParam("user", map.get("phoneNumber"));
			httpHelper.setPostParam("pass", map.get("password"));
			httpHelper.setPostParam("id", foodId);
			httpHelper.sendRequest();
			Log.i("TASKS", httpHelper.getResponse());
			this.setResponse(httpHelper.getResponse());
			return this.getResponse();
		}
		
	}
	
	public class SpoonFoodTask extends AbsHttpAsync{
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			if(this.getResponse() != null &&
					!this.getResponse().startsWith("error:")) {
				Map<String, String> res = JsonHelper.getInstance().reponseGetStat(this.getResponse());
				Toast toast = Toast.makeText(getApplicationContext(), res.get("msg"), Toast.LENGTH_SHORT);
				toast.show();
			}
			super.onPostExecute(result);
		}

		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			User user = new User(getApplicationContext());
			Map<String, String> map = user.getUserInfo();
			HttpHelper httpHelper = new HttpHelper();
			httpHelper.setPost(true);
			httpHelper.setUrl(Config.getInstance().get("baseUrl"));
			httpHelper.setPostParam("appId", "WBTOM");
			httpHelper.setPostParam("req", "RAT");
			httpHelper.setPostParam("user", map.get("phoneNumber"));
			httpHelper.setPostParam("pass", map.get("password"));
			httpHelper.setPostParam("id", foodId);
			httpHelper.setPostParam("meter", "SPOONS:"+params[0]);
			httpHelper.sendRequest();
			Log.i("TASKS", httpHelper.getResponse());
			this.setResponse(httpHelper.getResponse());
			return this.getResponse();
		}
		
	}
	
	public void setResponse(String response) {
		this.response = response;
	}
	
	public String getResponse() {
		return response;
	}

}
